package com.gitee.feizns.quickstart.ding.talk.api.v10.yida.forms;

import com.aliyun.dingtalkyida_1_0.Client;
import com.aliyun.dingtalkyida_1_0.models.ListTableDataByFormInstanceIdTableIdHeaders;
import com.aliyun.dingtalkyida_1_0.models.ListTableDataByFormInstanceIdTableIdRequest;
import com.aliyun.dingtalkyida_1_0.models.ListTableDataByFormInstanceIdTableIdResponse;
import com.aliyun.dingtalkyida_1_0.models.ListTableDataByFormInstanceIdTableIdResponseBody;
import com.aliyun.teautil.models.RuntimeOptions;
import com.gitee.feizns.quickstart.ding.talk.client.Clients;
import lombok.SneakyThrows;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 获取子表组件数据（/v1.0/yida/forms/innerTables/{formInstId}）
 * 接口路径：<a href="https://open.dingtalk.com/document/orgapp/obtain-child-table-component-data">获取子表组件数据（/v1.0/yida/forms/innerTables/{formInstId}）</a>
 * @link <a href="https://open.dingtalk.com/document/orgapp/obtain-child-table-component-data">服务端API 宜搭应用开发 表单 获取子表组件数据</a>
 * @author feizns
 * @since 2024/4/1
 */
public class InnerTables {

    /**
     * 请求头
     * @param accessToken 访问凭据
     * @return {@link ListTableDataByFormInstanceIdTableIdHeaders}
     */
    public static ListTableDataByFormInstanceIdTableIdHeaders headers(String accessToken) {
        ListTableDataByFormInstanceIdTableIdHeaders headers = new ListTableDataByFormInstanceIdTableIdHeaders();
        headers.xAcsDingtalkAccessToken = accessToken;
        return headers;
    }

    /**
     * 获取表单实例子组件数据
     * @param accessToken 访问凭据
     * @param formInstanceId 表单实例编号
     * @param req {@link ListTableDataByFormInstanceIdTableIdRequest}
     */
    @SneakyThrows
    public static List<Map<String, ?>> execute(String accessToken, String formInstanceId, ListTableDataByFormInstanceIdTableIdRequest req) {
        //客户端
        Client client = Clients.get(Client.class);
        //请求头
        ListTableDataByFormInstanceIdTableIdHeaders headers = headers(accessToken);
        int pageSize = 50;
        int pageNumber = 1;
        long total;
        List<Map<String, ?>> results = new ArrayList<>();
        //执行
        do {
            req.setPageSize(pageSize);
            req.setPageNumber(pageNumber);
            ListTableDataByFormInstanceIdTableIdResponse resp = client.listTableDataByFormInstanceIdTableIdWithOptions(formInstanceId, req, headers, new RuntimeOptions());
            ListTableDataByFormInstanceIdTableIdResponseBody body = resp.getBody();
            total = body.getTotalCount();
            results.addAll(body.getData());
        } while ( total > ((long) pageNumber++ * pageSize) );
        return results;
    }

}
